<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller\job;

use app\BaseController;
use think\facade\Db;
use app\wework\controller\Base;
use app\wework\controller\job\apiInfo;
use app\wework\model\BaseModel;
use app\wework\model\user\staff\StaffModel;
use app\wework\model\QyWechatApi;
use think\facade\Log;
use think\queue\Job;
/**
 * 客户阶段管理
 */
class TimedTask extends Base
{
	public function index(){
		$info = apiInfo::$info;
		$arr =  json_decode(file_get_contents('../app/wework/controller/job/index.txt'),1);
		$arr_api = [];
		$time = time();
		foreach ($info as $key => $val) {
			if($arr && array_key_exists($key, $arr)){
				if($time > $arr[$key] + ($val*60)){
					$arr[$key] = $time;
					$arr_api[] = $this->req->domain().'/wework/job/'.$key;
				}
			}else{
				$arr[$key] = $time;
				$arr_api[] = $this->req->domain().'/wework/job/'.$key;
			}
		}
		$arr_json = json_encode($arr);
		file_put_contents('../app/wework/controller/job/index.txt', $arr_json);
		if(count($arr_api) > 0){
			$this->exApi($arr_api);
		}
	}

	private function exApi($api){
		$mh = curl_multi_init();
		for ($i=0;$i<count($api);$i++) {
	     	$conn[$i]=curl_init($api[$i]);
			curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1);
			curl_setopt($conn[$i],CURLOPT_TIMEOUT,0);
			curl_setopt($conn[$i],CURLOPT_FOLLOWLOCATION,1);
			curl_multi_add_handle ($mh,$conn[$i]);
		}
		$active = null;
		do { $n=curl_multi_exec($mh,$active); }
		while ($active > 0);

		$result = true;
		for ($i=0;$i<count($api);$i++) {
			$res[$i] = json_decode(curl_multi_getcontent($conn[$i]),1);
			curl_close($conn[$i]);
			if($res[$i]['msg'] == 'error'){
				$result = false;
			}
		}
		if($result == false){
			echo 'fail';
		}
		echo 'success';
	}

}